package sk.stuba.fiit.ltasys.web.mvc.model.service.core;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Service;
import org.w3._2000._09.xmldsig.SignatureType;
import org.w3._2000._09.xmldsig.SignedInfoType;
import org.xml.sax.SAXException;

import sk.stuba.fiit.ltasys.ws.schema.beans.SignatureRequest;
import sk.stuba.fiit.ltasys.ws.schema.beans.Xadestype;

import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;

@Service("canonicalize")
public class Canonicalize {

	@Autowired 
	private Jaxb2Marshaller marshallerService;
	
	public SignatureRequest canonicalize(SignatureRequest xadestype) throws InvalidCanonicalizerException, CanonicalizationException, ParserConfigurationException, IOException, SAXException{	
		StringWriter writer = new StringWriter();
		Result result = new StreamResult(writer);
		marshallerService.marshal(xadestype, result);
		byte [] data = result.toString().getBytes();
		com.sun.org.apache.xml.internal.security.Init.init();
		Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
		byte canonXmlBytes[] = canon.canonicalize(data);
		String canonXmlString = new String(canonXmlBytes);
		
		ByteArrayInputStream bais = new ByteArrayInputStream(canonXmlString.getBytes());
		Source source = new StreamSource(bais);
		SignatureRequest stresult = (SignatureRequest) marshallerService.unmarshal(source);
		return stresult;
	}
}
